#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Log.hpp"
using namespace std;
using namespace LogModule;
void Usage(const std::string &process)
{
    cout<<"Usage: "<<process<<" server_ip server_port"<<endl; 
}

int main(int argc,char *argv[])

{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;

    }
    string serverip=argv[1];
    u_int16_t serverport=stoi(argv[2]);

    //1.socket
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        // LOG(LogLevel::FATAL) << "socket error";
       cerr<<"socket error"<<endl;
        return 1;
    }
    //2. connect
  struct sockaddr_in  server;
  memset(&server,0,sizeof(server));
  server.sin_family=AF_INET;
  server.sin_port=htons(serverport);
  inet_pton(AF_INET,serverip.c_str(),&server.sin_addr);
  int n=connect(sockfd,(const sockaddr*)&server,sizeof(server));
  if(n<0)
  {
     //LOG(LogLevel::FATAL) << "connect error";
    cerr<<"connect error"<<endl;
    return 2;
  }
  while(1)
  {
    string inbuffer;
    cout<<"Please Enter# ";
    getline(cin,inbuffer);
    ssize_t n=write(sockfd,inbuffer.c_str(),inbuffer.size());
    if(n>0)
    {
        char buffer[1024];
        ssize_t m=read(sockfd,buffer,sizeof(buffer)-1);
        if(m>0)
        {
            buffer[m]=0;
            cout<<"get a echo message ->"<<buffer<<endl;
        }
        else 
        {
            break;
        }
    }
    else
    {
        break;
    }

  }
  close(sockfd);
    return 0;
}